<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8" />
  <title>STOMP演示WebSocket</title>
</head>
<body onload="disconnect()">
<div>
  <div>
    <button id="connect" onclick="connect();">连接</button>
    <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button>
    <button id="subsOrg" disabled="disabled" onclick="subscribeOrg()">订阅</button>
    <button id="unSubsOrg" onclick="unSubscribeOrg()">取消订阅</button>
  </div>

  <div id="conversationDIV">
    <label>发送全局的信息V1</label>
    <input type="text" id="msg1" />
    <button id="sendMsgToAllV1" onclick="sendMsgToAllV1();">发送</button>
  </div>

  <div id="conversationDIV2">
    <label>发送全局的信息V2</label>
    <input type="text" id="msg2" />
    <button id="sendMsgToAllV2" onclick="sendMsgToAllV2();">发送</button>
  </div>

  <div id="conversationDIV3">
    <label>发送组内消息</label>
    <label>组名：</label><input type="text" id="orgNo" />
    <input type="text" id="msg3" />
    <button id="sendMsgToOrg" onclick="sendMsgToOrg();">发送</button>
  </div>

  <div id="conversationDIV4">
    <label>私聊V1</label>
    <label>对</label><input type="text" id="to1" /><label>说：</label>
    <input type="text" id="msg4" />
    <button id="sendMsgToSomeOneV1" onclick="sendMsgToSomeOneV1();">发送</button>
  </div>



  <p id="response"></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<!--<script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script>-->
<!--<script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.js"></script>-->
<script src="https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js"></script>
<script type="text/javascript">
  var stompClient = null;
  var subsOrg; //用来手动订阅、取消订阅

  const stompConfig = {
    //自定义的HEADERS，放登录成功后下发的JWT Token
    connectHeaders: {
      token: "leo1"
    },

    // 链接的URL，ws或wss。后面的ws与服务端的registry.addEndpoint("/ws")相匹配
    brokerURL: "ws://127.0.0.1:8080/ws",

    //生产环境去掉
    debug: function(str) {
      console.log('STOMP: ' + str);
    },

    // 如果断开连接，在5秒后重试
    reconnectDelay: 5000,
    // 上下行心跳间隔
    heartbeatIncoming: 10000,
    heartbeatOutgoing: 10000,

    // 订阅的操作要在onConnect内部完成，因为一旦重连，也得重新订阅，放在内部可以自动订阅。否则就要手动订阅
    onConnect: function(frame) {
      //订阅之后会有返回消息
      stompClient.subscribe('/topic/v1/broadcast/all', function(response) {
        showResponse(JSON.parse(response.body));
      });
      //订阅之后不会有返回消息
      stompClient.subscribe('/topic/v2/broadcast/all', function(response) {
        showResponse(JSON.parse(response.body));
      });
      //返回的对象可以使用unsubscribe()来取消订阅
      subsOrg = stompClient.subscribe('/topic/broadcast/orgA', function(response) {
        showResponse(JSON.parse(response.body));
      });
      //单对单接收，需在URL前加/user，对应的服务端配置是registry.setUserDestinationPrefix("/user")
      stompClient.subscribe('/user/topic/v1/mymsg', function(response) {
        showResponse(JSON.parse(response.body));
      });
    },
    onStompError: function(frame) {
      //TOKEN验证失败抛出的异常会在此处处理
      setConnected(false);
      console.log(frame.headers.message);
    }
  };

  //取消订阅
  function unSubscribeOrg() {
    subsOrg.unsubscribe();
    document.getElementById('unSubsOrg').disabled = true;
    document.getElementById('subsOrg').disabled = false;
  }

  //手动订阅
  function subscribeOrg() {
    subsOrg = stompClient.subscribe('/topic/broadcast/orgA', function(response) {
      showResponse(JSON.parse(response.body));
    });
    document.getElementById('unSubsOrg').disabled = false;
    document.getElementById('subsOrg').disabled = true;
  }


  function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    if(!connected){
      document.getElementById('unSubsOrg').disabled = connected;
      document.getElementById('subsOrg').disabled = !connected;
      $('#response').html("");
    }

    document.getElementById('conversationDIV').style.visibility = connected ? 'visible' : 'hidden';
    document.getElementById('conversationDIV2').style.visibility = connected ? 'visible' : 'hidden';
    document.getElementById('conversationDIV3').style.visibility = connected ? 'visible' : 'hidden';
    document.getElementById('conversationDIV4').style.visibility = connected ? 'visible' : 'hidden';
  }

  function connect() {
    stompClient = new StompJs.Client(stompConfig);
    stompClient.activate();
    setConnected(true);
    console.log("已连接");
  }

  function disconnect() {
    if (stompClient != null) {
      stompClient.deactivate();
    }
    setConnected(false);
    console.log("断开连接");
  }

  function sendMsgToAllV1() {
    var msg1 = $('#msg1').val();
    let param1 = {
      from: "leo1",
      to: "all",
      msg: msg1
    }
    //注意stomp-websocket与stompjs的写法
    //stompClient.publish("/v1/sendMsgToAll",{},param1);
    stompClient.publish({
      destination: '/v1/sendMsgToAll',
      body: JSON.stringify(param1)
    });
  }

  function sendMsgToAllV2() {
    var msg2 = $('#msg2').val();
    let param2 = {
      from: "leo1",
      to: "all",
      msg: msg2
    }
    stompClient.publish({
      destination: '/v2/sendMsgToAll',
      body: JSON.stringify(param2)
    });
  }

  function sendMsgToOrg() {
    var orgNo = $('#orgNo').val();
    var msg3 = $('#msg3').val();
    let param3 = {
      from: "leo1",
      to: orgNo,
      msg: msg3
    }
    stompClient.publish({
      destination: '/sendMsgToOrg/' + orgNo,
      body: JSON.stringify(param3)
    });
  }

  function sendMsgToSomeOneV1() {
    var to1 = $('#to1').val();
    var msg4 = $('#msg4').val();
    let param4 = {
      from: "leo1",
      to: to1,
      msg: msg4
    }
    stompClient.publish({
      destination: '/v1/sendMsgToSomeOne/' + to1,
      body: JSON.stringify(param4)
    });
  }

  function showResponse(message) {
    $('#response').append($('#response').val() + message.data.msg + '<br/>');
  }
</script>
</body>
</html>